package com.ttbj.controller.withdraw;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ttbj.api.company.CompanyService;
import com.ttbj.api.dto.Page;
import com.ttbj.api.dto.SalesmanDto;
import com.ttbj.api.dto.WithdrawData;
import com.ttbj.api.exception.BusinessException;
import com.ttbj.api.yitong.WithdrawService;
import com.ttbj.constant.Const;
import com.ttbj.constant.FlagEnum;
import com.ttbj.constant.PlatFormErrorCode;
import com.ttbj.util.ViewDataUtil;



@Controller
public class WithdrawController {
	
	@Autowired
	private WithdrawService withdrawService;
	@Autowired
	private CompanyService companyService;
	
	/**
	 * 提现列表页面
	 * @return
	 */
	@RequestMapping(value="/withdraw/withdraw_list.htm")
	public String withdraw_list() {
		return "withdraw/withdraw_list";
	}
	
	/**
	 * 提现日志页面
	 * @return
	 */
	@RequestMapping(value="/withdraw/withdraw_log.htm")
	public String withdraw_log() {
		return "withdraw/withdraw_log";
	}
	
	/**
	 * 设置提现密码
	 * @return
	 */
	@RequestMapping(value="/withdraw/withdraw_pass.htm")
	public String withdraw_pass() {
		return "withdraw/withdraw_pass";
	}
	
	/**
	 * 修改提现密码
	 * @return
	 */
	@RequestMapping(value="/withdraw/withdraw_edit_pass.htm")
	public String withdraw_edit_pass() {
		return "withdraw/withdraw_edit_pass";
	}
	
	/**
	 * 提现页面
	 * @return
	 */
	@RequestMapping(value="/withdraw/withdraw_page.htm")
	public String withdraw_page() {
		return "withdraw/withdraw_page";
	}
	
	
	/**
	 * 检测公司的提现密码是否设置
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/withdraw/checkWdPwd.htm", method=RequestMethod.GET, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	public String checkWdPwd(HttpServletRequest request) {
		//获取登陆人信息
		SalesmanDto salesmanDto = (SalesmanDto) request.getSession().getAttribute(Const.TTBJ_USER_SESSION_KEY);
		//获取角色名称，只有角色为公司管理员的人员才能提现
		String roleName = salesmanDto.getRoleDto().getRoleName();
		if (!roleName.equals("admin")) {
			return ViewDataUtil.buildFailureJson(FlagEnum.NO_AUTO.code(), "无此权限！");
		}
		//获取加密的提现密码
		String jiamiWdPwd = this.companyService.findWdPasswordByNum(salesmanDto.getSalesmanComnum());
		if (StringUtils.isBlank(jiamiWdPwd)) {	//如果加密密码为null或者‘’，则提示进行设置提现密码
			return ViewDataUtil.buildFailureJson(PlatFormErrorCode.DATA_SECURITY.code(), "请先设置提现密码");
		}
		return ViewDataUtil.buildSuccessJson("已设置提现密码");
	}
	
	/**
	 * 使用易通金服提现接口完成公司提现业务
	 * @param request
	 * @param response
	 * @param wdPassword 提现密码
	 * @param accountNo 账户号
	 * @param amount 提现金额
	 * @param personNum 提现人编号
	 * @param personName 提现人用户名
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/withdraw/withdraw.htm", method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	public String withdraw(HttpServletRequest request, HttpServletResponse response,
						   @RequestParam String wdPassword,
						   @RequestParam String accountNo,
						   @RequestParam String amount) throws Exception{
		//获取登陆人信息
		SalesmanDto salesmanDto = (SalesmanDto) request.getSession().getAttribute(Const.TTBJ_USER_SESSION_KEY);
		String personNum = salesmanDto.getSalesmanNum();	//获取登陆人编号
		String personName = salesmanDto.getSalesmanName();	//获取登陆人的用户名
		//提现操作
		Map<String, String> map = this.withdrawService.withrawOperation(wdPassword, accountNo, amount, personNum, personName);
		//获取返回的status
		int status = Integer.parseInt(map.get("status"));
		//获取返回的描述
		String retInfo = map.get("retInfo");
		//如果是返回1，则说明受理成功
		if (status == 1) {
			return ViewDataUtil.buildSuccessJson(retInfo);
		}
		return ViewDataUtil.buildFailureJson(1, retInfo);
	}
	
	
	/**
	 * 易通金服提现通知
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/withdraw/withdraw_notify.htm")
	public void withdraw_notify(HttpServletRequest request, HttpServletResponse response) {
		try {
			//从body中获取报文生成字符串
			String noticeStr = readAsChars(request);
			Map<String, String> notifyMap = this.withdrawService.withrawNotify(noticeStr);
			for (Map.Entry<String, String> entry : notifyMap.entrySet()) {
				System.out.println("提现通知：" + entry.getKey() + "->" + entry.getValue());
			}
			String status = notifyMap.get("status");
			if (status.equals("2")) {	//如果status为2，则说明是提现成功，但更新提现状态失败，则需要重新回调
				response.getWriter().println("failed");
			}else {
				response.getWriter().print("success");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 使用易通金服提现查询，查询提现的状态：00：成功，01：失败，02处理中，03：待请求，04：网络异常.
	 * 如果查询出来的状态跟前端传来的状态不同，则更新状态，否则，不更新.
	 * @param request
	 * @param accountNo 账户号
	 * @param orderNo 提现订单号（分账系统订单号）
	 * @param status 前端传来的提现状态值
	 * @return
	 */
	@RequestMapping(value="/withdraw/withrawQuery.htm", method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	public String withrawQuery(HttpServletRequest request, @RequestParam String accountNo, 
										@RequestParam String orderNo, @RequestParam String status) {
		try {
			Map<String, String> wdQueryMap = this.withdrawService.withrawQuery(accountNo, orderNo, status);
			if (wdQueryMap.get("status").equals("1")) {
				return ViewDataUtil.buildSuccessJson(wdQueryMap.get("wdQueryStatus"));
			}else {
				return ViewDataUtil.buildFailureJson(1, wdQueryMap.get("retInfo"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ViewDataUtil.buildFailureJson(1, "数据有错误！");
	}
	
	/**
	 * 分页和查询条件查询提现信息
	 * @param request
	 * @param withdrawData 提现相关查询信息
	 * @param page 分页页码
	 * @return
	 */
	@RequestMapping(value="/withdraw/getWithdrawResultByPage.htm", method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	public String getWithdrawResultByPage(HttpServletRequest request, WithdrawData withdrawData, Page page) {
		try {
			System.out.println(withdrawData.toString());
			List<WithdrawData> withdrawDatas = this.withdrawService.findWithdrawResultByPage(withdrawData, page);
			int count = 0;
			if (null != withdrawDatas) {
				count = this.withdrawService.findWithdrawResultByPageCount(withdrawData);
			}
			return ViewDataUtil.buildSuccessPageJson("提现信息查询成功", withdrawDatas, count);
		} catch (BusinessException e) {
			return ViewDataUtil.buildFailureJson(e.getErrorCode(), e.getMessage());
		}
	}
	
	
	/**
	 * 分页和查询条件查询提现日志
	 * @param request
	 * @param withdrawData 提现相关查询信息
	 * @param page 分页页码
	 * @return
	 */
	@RequestMapping(value="/withdraw/withdrawLog.htm", method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	public String withdrawLog(HttpServletRequest request, String startDate, String endDate, Page page) {
		try {
			//获取登陆人信息
			SalesmanDto salesmanDto = (SalesmanDto) request.getSession().getAttribute(Const.TTBJ_USER_SESSION_KEY);
			//获取角色名称，只有角色为公司管理员的人员才能设置提现密码
			String roleName = salesmanDto.getRoleDto().getRoleName();
			if (!roleName.equals("admin")) {
				return ViewDataUtil.buildFailureJson(FlagEnum.NO_AUTO.code(), "无此权限！");
			}
			WithdrawData withdrawData = new WithdrawData();
			withdrawData.setStartDate(startDate);
			withdrawData.setEndDate(endDate);
			withdrawData.setPersonNum(salesmanDto.getSalesmanNum());
			List<WithdrawData> withdrawDatas = this.withdrawService.findWithdrawLogByPage(withdrawData, page);
			int count = 0;
			if (null != withdrawDatas) {
				count = this.withdrawService.findWithdrawLogByPageCount(withdrawData);
			}
			return ViewDataUtil.buildSuccessPageJson("提现日志查询成功", withdrawDatas, count);
		} catch (BusinessException e) {
			return ViewDataUtil.buildFailureJson(e.getErrorCode(), e.getMessage());
		}
	}
	
	/**
	 * 设置企业的提现密码
	 * @param request
	 * @param wdPassword 提现密码
	 * @return
	 */
	@RequestMapping(value="/withdraw/setUpComnumWpassword.htm", method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	public String setUpComnumWpassword(HttpServletRequest request, @RequestParam String wdPassword) {
		//获取登陆人信息
		SalesmanDto salesmanDto = (SalesmanDto) request.getSession().getAttribute(Const.TTBJ_USER_SESSION_KEY);
		//获取角色名称，只有角色为公司管理员的人员才能设置提现密码
		String roleName = salesmanDto.getRoleDto().getRoleName();
		if (!roleName.equals("admin")) {
			return ViewDataUtil.buildFailureJson(FlagEnum.NO_AUTO.code(), "无此权限！");
		}
		try {
			String comnumNum = salesmanDto.getSalesmanComnum();	//获取公司编号
			String salesmanName = salesmanDto.getSalesmanName();
			//设置提现密码
			this.withdrawService.setUpComnumWdPassword(comnumNum, salesmanName, wdPassword);
			return ViewDataUtil.buildSuccessJson("提现密码设置成功！");
		} catch (BusinessException e) {
			return ViewDataUtil.buildFailureJson(e.getErrorCode(), e.getMessage());
		}
	}
	
	/**
	 * 修改企业的提现密码
	 * @param request
	 * @param wdPassword 提现密码
	 * @return
	 */
	@RequestMapping(value="/withdraw/modifyComnumWpassword.htm", method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	public String modifyComnumWpassword(HttpServletRequest request, @RequestParam String oldWdPassword, @RequestParam String newWdPassword) {
		//获取登陆人信息
		SalesmanDto salesmanDto = (SalesmanDto) request.getSession().getAttribute(Const.TTBJ_USER_SESSION_KEY);
		//获取角色名称，只有角色为公司管理员的人员才能设置提现密码
		String roleName = salesmanDto.getRoleDto().getRoleName();
		if (!roleName.equals("admin")) {
			return ViewDataUtil.buildFailureJson(FlagEnum.NO_AUTO.code(), "无此权限！");
		}
		try {
			String comnumNum = salesmanDto.getSalesmanComnum();	//获取公司编号
			String salesmanName = salesmanDto.getSalesmanName();
			//修改提现密码
			this.withdrawService.modifyComnumWdPassword(comnumNum, salesmanName, oldWdPassword, newWdPassword);
			return ViewDataUtil.buildSuccessJson("提现密码修改成功！");
		} catch (BusinessException e) {
			return ViewDataUtil.buildFailureJson(e.getErrorCode(), e.getMessage());
		}
	}
	
	/**
	 * 从 HttpServletRequest 中读取HTTP请求的body内容
	 * @param request HttpServletRequest对象
	 * @return body里的内容
	 */
	private String readAsChars(HttpServletRequest request) {
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder("");
		try {
			br = request.getReader();
			String str;
			while((str = br.readLine()) != null) {
				sb.append(str);
			}
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}
	
}
